package com.pfzy.utildemo.activity.record.soundrecord.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

//import com.pfzy.sdk.basis.tool.utils.NumberUtil;
//import com.pfzy.sdk.soundrecord.constatns.SoundRecordConstant;
//import com.pfzy.sdk.soundrecord.sqlDTO.AudioFileInfoDao;
//import com.pfzy.sdk.soundrecord.sqlDTO.DaoMaster;
//import com.pfzy.sdk.soundrecord.sqlDTO.DaoSession;
//import com.pfzy.sdk.soundrecord.util.Logger;
//import com.pfzy.sdk.soundrecord.util.TimeUtil;

import com.pfzy.utildemo.activity.db.DaoMaster;
import com.pfzy.utildemo.activity.db.DaoSession;
import com.pfzy.lib.config.log.MyLog;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * 数据库管理器
 */
public class DbManager {
    private static DbManager mInstance = null;
    private Context mContext;
    private DaoSession mDaoSession;

    public static DbManager getInstance() {
        if (mInstance == null) {
            synchronized (DbManager.class) {
                if (mInstance == null) {
                    mInstance = new DbManager();
                }
            }
        }
        return mInstance;
    }

    private DbManager() {
    }

    public void init(Context context) {
        this.mContext = context;
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "audioFile.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        this.mDaoSession = daoMaster.newSession();
    }

//    public List<AudioFileInfo> queryAll() {
//        List<AudioFileInfo> fileInfos = this.mDaoSession.loadAll(AudioFileInfo.class);
//        return fileInfos;
//    }
//
//    /**
//     * 插入一条记录，表里面要没有与之相同的记录
//     */
//    public void insert(AudioFileInfo data) {
//        Logger.i(TAG, "insert()=" + data);
//        this.mDaoSession.insertOrReplace(data);
//    }
//
//    /**
//     * 根据组ID查询 未上传的 文件列表
//     * 排序 记录开始时间
//     *
//     * @param groupId
//     * @return
//     */
//    public List<AudioFileInfo> queryByGroupIdAndNotUploadAndReturnAsc(String groupId) {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class);
//        queryBuilder.where(AudioFileInfoDao.Properties.Groupid.eq(groupId))
//                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.eq(SoundRecordConstant.UploadStatus.NO_UPLOAD))
//                .orderAsc(AudioFileInfoDao.Properties.RecordStartTime);
//        List<AudioFileInfo> list = queryBuilder.list();
//        Logger.i(TAG, "queryByGroupIdAndNotUploadAndReturnAsc() -> " + list);
//        return list;
//    }
//
//    /**
//     * 根据组ID查询 录音完成 但 未上传的 文件列表
//     * 排序 记录开始时间
//     *
//     * @param groupId
//     * @return
//     */
//    public List<AudioFileInfo> queryByGroupIdAndRecordDoneAndNotUploadAndReturnAsc(String groupId) {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class);
//        queryBuilder.where(AudioFileInfoDao.Properties.Groupid.eq(groupId))
//                .where(AudioFileInfoDao.Properties.RecordStatus.eq(SoundRecordConstant.RecordStatus.RECORD_DONE))
//                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.eq(SoundRecordConstant.UploadStatus.NO_UPLOAD))
//                .orderAsc(AudioFileInfoDao.Properties.RecordStartTime);
//        List<AudioFileInfo> list = queryBuilder.list();
//        Logger.i(TAG, "queryByGroupIdAndRecordDoneAndNotUploadAndReturnAsc() -> " + list);
//        return list;
//    }

    public AudioFileInfo queryByFilePath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class);
        queryBuilder.where(AudioFileInfoDao.Properties.AudioFilePath.eq(filePath));
        List<AudioFileInfo> list = queryBuilder.list();
        if (list == null || list.size() == 0) {
            _logd("queryByFilePath() 查询结果为null");
            return null;
        }
        if (list.size() > 1) {
            _loge("queryByFilePath 长度异常 ->" + list);
        }
        AudioFileInfo returnFile = list.get(0);
        _logd("queryByFilePath() -> " + returnFile);
        return returnFile;
    }

//    public void update(AudioFileInfo fileInfo) {
//        this.mDaoSession.update(fileInfo);
//    }

    /**
     * 按文件路径查询并更新上传状态
     */
    public void queryByFilePathAndUpdateUploadStatus(String filePath, int uploadStatus) {
        AudioFileInfo fileInfo = queryByFilePath(filePath);
        fileInfo.setAudioFileUploadStatus(uploadStatus);
        this.mDaoSession.update(fileInfo);
    }

//    /**
//     * 按文件路径查询并更新上传状态
//     *
//     * @param fileInfo
//     * @param uploadStatus
//     */
//    public void queryByFilePathAndUpdateUploadStatus(AudioFileInfo fileInfo, int uploadStatus) {
//        queryByFilePathAndUpdateUploadStatus(fileInfo.getAudioFilePath(), uploadStatus);
//    }
//
//    /**
//     * 按文件路径查询并更新上传状态和指针
//     *
//     * @param filePath
//     * @param uploadStatus
//     * @param position
//     */
//    public void queryByFilePathAndUpdateUploadStatusAndPosition(String filePath, int uploadStatus, long position) {
//        AudioFileInfo fileInfo = queryByFilePath(filePath);
//        fileInfo.setAudioFileUploadStatus(uploadStatus);
//        fileInfo.setPosition("" + position);
//        this.mDaoSession.update(fileInfo);
//    }
//
//    public long queryStartTimeStampByGroupId(String groupid) {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class);
//        queryBuilder.where(AudioFileInfoDao.Properties.Groupid.eq(groupid))
//                .orderAsc(AudioFileInfoDao.Properties.RecordStartTime);
//        List<AudioFileInfo> list_6 = queryBuilder.list();
//        if (list_6 == null || list_6.size() == 0) {
//            Logger.e(TAG, "queryStartTimeStampByGroupId() 查询数量为0");
//            return 0L;
//        }
//        return list_6.get(0).getRecordStartTime();
//    }
//
//    public void queryByFilePathAndUpdatePosition(String path, long position) {
//        AudioFileInfo fileInfo = queryByFilePath(path);
//        fileInfo.setPosition(String.valueOf(position));
//        this.mDaoSession.update(fileInfo);
//    }
//
//    public long queryPreviousPositionByFileInfo(AudioFileInfo fileInfo) {
//        if (fileInfo == null || fileInfo.getExtraCount() == 0) {
//            return 0L;
//        }
//        int extraInt = fileInfo.getExtraCount() - 1;
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class)
//                .where(AudioFileInfoDao.Properties.Groupid.eq(fileInfo.getGroupid()))
//                .where(AudioFileInfoDao.Properties.ExtraCount.eq(Integer.valueOf(extraInt)));
//        List<AudioFileInfo> list_3 = queryBuilder.list();
//        Logger.i(TAG, "queryPreviousPositionByFileInfo() -> 查询结果 list3=" + list_3);
//        if (list_3 == null || list_3.size() == 0) {
//            Logger.e(TAG, "queryPreviousPositionByFileInfo() -> 查询出来的状态异常 长度为0" + fileInfo.getAudioFilePath());
//            return 0L;
//        }
//        if (list_3.size() > 1) {
//            Logger.e(TAG, "queryPreviousPositionByFileInfo() -> 查询出来的状态异常, 长度>1 list3=" + list_3);
//        }
//        String positionStr = list_3.get(0).getPosition();
//        if (!TextUtils.isEmpty(positionStr)) {
//            return NumberUtil.toLong(positionStr);
//        }
//        return 0L;
//    }
//
//    public List<AudioFileInfo> queryByGruopId(String groupId) {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class).where(AudioFileInfoDao.Properties.Groupid.eq(groupId));
//        List<AudioFileInfo> list_4 = queryBuilder.list();
//        return list_4;
//    }
//
//    public void updateGroupTaskByGruopId(String groupId, boolean isAllUploadDone) {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class).where(AudioFileInfoDao.Properties.Groupid.eq(groupId));
//        List<AudioFileInfo> list_5 = queryBuilder.list();
//        if (list_5 != null && list_5.size() != 0) {
//            for (int i = 0; i < list_5.size(); i++) {
//                list_5.get(i).setGroupTask(isAllUploadDone);
//            }
//            for (AudioFileInfo fileInfo_5 : list_5) {
//                this.mDaoSession.update(fileInfo_5);
//            }
//        }
//    }
//
//    public List<AudioFileInfo> queryByNotuploadAndStartTimeLtCurrent() {
//        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class)
//                .where(AudioFileInfoDao.Properties.RecordStartTime.lt(Long.valueOf(TimeUtil.currentTimeMillis())))
//                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.eq(0))
//                .orderAsc(AudioFileInfoDao.Properties.RecordStartTime).limit(1000);
//        List<AudioFileInfo> list_6 = queryBuilder.list();
//        return list_6;
//    }

    /**
     * 查询不上传成功和开始时间小于当前时间
     */
    public List<AudioFileInfo> queryByNotuploadSuccAndStartTimeLtCurrentAndDesc() {
        QueryBuilder<AudioFileInfo> queryBuilder = this.mDaoSession.queryBuilder(AudioFileInfo.class)
                .where(AudioFileInfoDao.Properties.RecordStartTime.lt(System.currentTimeMillis()))
                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.notEq(2))
                .orderDesc(AudioFileInfoDao.Properties.RecordStartTime)
                .limit(1000);
        List<AudioFileInfo> list = queryBuilder.list();
        return list;
    }

//    public void queryFilePathAndPosition0UpdateUploadStatus(List<String> filePathList, int uploadPosition) {
//        for (String filePath : filePathList) {
//            AudioFileInfo fileInfo = queryByFilePath(filePath);
//            if (fileInfo != null && TextUtils.equals(fileInfo.getPosition(), SoundRecordConstant.AUDIO_FILE_INFO_POSITION_ZERO)) {
//                fileInfo.setAudioFileUploadStatus(uploadPosition);
//                update(fileInfo);
//            }
//        }
//    }
//
//    /**
//     * 分组ID列表
//     *
//     * @return
//     */
//    public Set<String> queryGroudIdList() {
//        List<AudioFileInfo> list = this.mDaoSession.queryBuilder(AudioFileInfo.class)
//                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.eq(SoundRecordConstant.UploadStatus.UPLOAD_DONE))
//                .where(new WhereCondition.StringCondition("1 GROUP BY groupid"))
//                .orderDesc(AudioFileInfoDao.Properties.RecordStartTime)
//                .list();
//        Logger.i(TAG, "queryGroudIdList() ->list=" + list);
//        Set<String> groupSet = new HashSet<>();
//        for (AudioFileInfo file : list) {
//            groupSet.add(file.getGroupid());
//        }
//        return groupSet;
//    }
//
//    /**
//     * 根据组ID查询上传完成的
//     *
//     * @param groupId
//     * @return
//     */
//    public List<AudioFileInfo> queryByGroupIdAndNotUploadDone(String groupId) {
//        List<AudioFileInfo> qb = this.mDaoSession.queryBuilder(AudioFileInfo.class)
//                .where(AudioFileInfoDao.Properties.Groupid.eq(groupId))
//                .where(AudioFileInfoDao.Properties.AudioFileUploadStatus.notEq(SoundRecordConstant.UploadStatus.UPLOAD_DONE))
//                .list();
//        Logger.i(TAG, "queryByGroupIdAndNotUploadDone() -> " + qb);
//        return qb;
//    }
//
//    /**
//     * 删除对应的组ID
//     *
//     * @param groupId
//     */
//    public void deleteGroup(String groupId) {
//        this.mDaoSession.queryBuilder(AudioFileInfo.class)
//                .where(AudioFileInfoDao.Properties.Groupid.eq(groupId))
//                .buildDelete()
//                .executeDeleteWithoutDetachingEntities();
//    }

    private void _logd(String msg) {
        MyLog.logd("录音存储管理 " + msg);
    }

    private void _loge(String msg) {
        MyLog.loge("录音存储管理 " + msg);
    }
}
